package cas.ihep.hadoop.util;

import cas.ihep.fs.UnifiedBlock;
import cas.ihep.fs.UnifiedFile;

import java.io.Closeable;
import java.io.IOException;

public abstract class HadoopHepFile implements HadoopLuaOopEngine.HepFile,Closeable{

    protected UnifiedFile file;
    protected UnifiedBlock block;
    protected boolean isRead;
    protected boolean isOpen;

    public abstract void reopen();
    public HadoopHepFile(UnifiedFile f,boolean read){
        file=f;
        isRead=read;
        isOpen=true;
        try{
            if(read){
                block=f.block(0);
            }else{
                block=f.next();
            }
        }catch (IOException ignored){}
    }

    @Override
    public int fd() {
        return file.hashCode();
    }

    @Override
    public String baseName() {
        String n=fileName();
        int index=n.indexOf('.');
        return index==-1?n:n.substring(0,index);
    }

    @Override
    public String fileName() {
        String p=path();
        int index=p.lastIndexOf('/');
        return index==-1?p:p.substring(index+1);
    }

    @Override
    public String path() {
        return file.path().toString();
    }

    @Override
    public String absolutePath() {
        try {
            if(!isRead && !isOpen){
                reopen();
            }
            return block.absolutePath();
        }catch (IOException e){
            return "";
        }
    }

    @Override
    public void persist() {
        try {
            file.persist();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void free() {
        try{
            file.free();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete() {
        try{
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws IOException {
        if(!isOpen){
            return;
        }
        isOpen=false;
        try {
            file.close();
        }catch (Exception e){
            file.delete();
            System.err.println("IOException catched: "+file.path());
            e.printStackTrace();
            for(Throwable t:e.getSuppressed()){
                t.printStackTrace();
            }
            throw new IOException(e);
        }
    }

    public void complete()throws IOException{
        close();
    }
}
